/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.jeff.springWebTestNG.tx;

import java.util.logging.Level;
import java.util.logging.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionSynchronizationManager;

/**
 *
 * @author winnie
 */
//@Component //temporary disable this advice, seems impossible to set a ordered 
            //'around'or'after' advice leaves BEFORE the @Transactional/txAdvice
@Aspect
public class TransactionAwareAuditAspect implements Ordered, ApplicationEventPublisherAware {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    
    @Override
    public int getOrder() {
        return 200;
    }

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
        this.applicationEventPublisher = applicationEventPublisher;
    }
    
    
    @Around("tryDoingSth()")
    public void flushAuditQueue(ProceedingJoinPoint pjp) {
        System.out.println("begin of flushAuditQueue()");
        try {
            pjp.proceed();
        } catch (Throwable ex) {
            Logger.getLogger(TestTxAspect.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("at the end of flushAuditQueue() isSynchronizationActive = " + 
                TransactionSynchronizationManager.isSynchronizationActive());
//        applicationEventPublisher.publishEvent(new TransactionAwareEvent(this));
    }
    
    @Pointcut("execution(* com.jeff.springWebTestNG.persistence.service.IGenericMyBatisPersister.tryDoingSth(..))")
    public void tryDoingSth() {}
}
